<?php


/**
*读文件函数
**/
function read_file($filename,$method="rb")
{
    $filedata='';
	if($handle=@fopen($filename,$method))
	{
		@flock($handle,LOCK_SH);
		$filedata=@fread($handle,@filesize($filename));
		@fclose($handle);
	}
	return $filedata;
}

/**
*写文件函数
**/
function write_file($filename,$data,$method="rb+",$iflock=1)
{
	@touch($filename);
	$handle=@fopen($filename,$method);
	if($iflock)
	{
		@flock($handle,LOCK_EX);
	}
	@fputs($handle,$data);
	
	if($method=="rb+")
	{
	    @ftruncate($handle,strlen($data));
	}
	
	@fclose($handle);
	@chmod($filename,0777);	
	if( is_writable($filename) )
	{
		return 1;
	}else
	{
		return 0;
	}
}



function write_router_cache($data,$type="add")
{
    $file = ROOT_PATH.'/data/router/router.php';
	$tempdata = include($file);
	if($type=="add") {
	    $tempdata = $tempdata + $data ;	
	} else if ($type=="edit") {
	    foreach ( $data as $key => $value ) {
		    $catid = $value['catid'];
			$name = $key;
			$zhi =$value;
		}	
	    foreach ( $tempdata as $key => $value ) {
		    if($value['catid']==$catid) {
			    unset($tempdata[$key]);				
			}
		}
		$tempdata[$name] = $zhi;
	} else if ($type=="del") {
	    foreach ( $tempdata as $key => $value ) {
		    if($value['catid']==$data) {
			    unset($tempdata[$key]);				
			}
		}	   
	}
	write_file($file, "<?php \nreturn " . var_export($tempdata , true) . ";\n?>");	
}


/**
*删除文件,值不为空，则返回不能删除的文件名
**/
function del_file($path)
{
    $show ="";
	if (file_exists($path))
	{
		if(is_file($path))
		{
			if(	!@unlink($path)	)
			{
				$show.="$path,";
			}
		} 
		else
		{
			$handle = opendir($path);
			while (($file = readdir($handle))!='') 
			{
				if (($file!=".") && ($file!="..") && ($file!=""))
				{
					if (is_dir("$path/$file"))
					{
						$show.=del_file("$path/$file");
					} 
					else
					{
						if( !@unlink("$path/$file") )
						{
							$show.="$path/$file,";
						}
					}
				}
			}
			closedir($handle);
			if(!@rmdir($path))
			{
				$show.="$path,";
			}
		}
	}
	return $show;
}

/*
将数组中值为空的的值去除
*/
function del_empty_var($array){
    
	 foreach($array as $key => $value)
	 {
	     if(empty($value))
	     {
	      unset($array[$key]);
	     }
	 
	 }
	
	return $array;
}


//多维数组按$k值排序$arr多维数组 
function array_var_sort(&$arr,$k)
{   
	  if(empty($k))return false;
	  $list=array();		  
      foreach ($arr as $key => $value) 
	  { 

         $list[$key] = $value[$k]; 
      } 
	  if(!is_array($list))return false;	  
      array_multisort($list, $arr);

}





if(!function_exists('json_encode')) 
{
	function json_encode($arg) 
	{
		$returnValue = '';
		$c           = '';
		$i           = '';
		$l           = '';
		$s           = '';
		$v           = '';
		$numeric     = true;

		switch (gettype($arg))
		 {
			case 'array':
				foreach ($arg AS $i => $v) 
				{
					if (!is_numeric($i)) 
					{
						$numeric = false;
						break;
					}
				}

				if ($numeric) 
				{
					foreach ($arg AS $i => $v) 
					{
						if (strlen($s) > 0) 
						{
							$s .= ',';
						}
						$s .= json_encode($arg[$i]);
					}

					$returnValue = '[' . $s . ']';
				} 
				else 
				{
					foreach ($arg AS $i => $v) 
					{
						if (strlen($s) > 0) 
						{
							$s .= ',';
						}
						$s .= json_encode($i) . ':' . json_encode($arg[$i]);
					}

					$returnValue = '{' . $s . '}';
				}
				break;

			case 'object':
				foreach (get_object_vars($arg) AS $i => $v) 
				{
					$v = json_encode($v);

					if (strlen($s) > 0) 
					{
						$s .= ',';
					}
					$s .= json_encode($i) . ':' . $v;
				}

				$returnValue = '{' . $s . '}';
				break;

			case 'integer':
			case 'double':
				$returnValue = is_numeric($arg) ? (string) $arg : 'null';
				break;

			case 'string':
				$returnValue = '"' . strtr($arg, array(
					"\r"   => '\\r',    "\n"   => '\\n',    "\t"   => '\\t',     "\b"   => '\\b',
					"\f"   => '\\f',    '\\'   => '\\\\',   '"'    => '\"',
					"\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002', "\x03" => '\u0003',
					"\x04" => '\u0004', "\x05" => '\u0005', "\x06" => '\u0006', "\x07" => '\u0007',
					"\x08" => '\b',     "\x0b" => '\u000b', "\x0c" => '\f',     "\x0e" => '\u000e',
					"\x0f" => '\u000f', "\x10" => '\u0010', "\x11" => '\u0011', "\x12" => '\u0012',
					"\x13" => '\u0013', "\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',
					"\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019', "\x1a" => '\u001a',
					"\x1b" => '\u001b', "\x1c" => '\u001c', "\x1d" => '\u001d', "\x1e" => '\u001e',
					"\x1f" => '\u001f'
				)) . '"';
				break;

			case 'boolean':
				$returnValue = $arg?'true':'false';
				break;

			default:
				$returnValue = 'null';
		}

		return $returnValue;
	}
}



function set_cookie($name,$value='',$time=0,$cookie_path='/',$cookie_domain='',$cookie_secure=false) 
{
	if(setcookie(COOKIE_PREFIX.$name,$value,$time,$cookie_path,$cookie_domain,$cookie_secure))
	{
	     return true;
	}
	else
	{
	     return false;
	}
}

function get_cookie($name)
{   
    if(empty($name)&&!isset($_COOKIE[COOKIE_PREFIX.$name]))
	{
        return '';	
	}
	else
	{
	    if(isset($_COOKIE[COOKIE_PREFIX.$name]))
		{
        return $_COOKIE[COOKIE_PREFIX.$name];			
		}
		else
		{
        return '';			
		}

	}
}

//给cookie赋值
function assign_cookie($name,$value)
{
    $_COOKIE[COOKIE_PREFIX.$name]=$value;
}




/**
 * 如果系统不存在file_put_contents函数则声明该函数
 *
 * @author  wj
 * @param   string  $file
 * @param   mix     $data
 * @return  int
 */
if (!function_exists('file_put_contents'))
{
    if (!defined('LOCK_EX'))
    {
        define('LOCK_EX', 'LOCK_EX');
    }
    function file_put_contents($file, $data, $mode = '')
    {
        $contents = (is_array($data)) ? implode('', $data) : $data;

        $mode = (empty($mode)) ? 'ab+' : 'wb';

        if (($fp = @fopen($file, $mode)) === false)
        {
            return false;
        }
        else
        {
            $bytes = fwrite($fp, $contents);
            fclose($fp);

            return $bytes;
        }
    }
}



/* //生成目录
function get_dir($path)
{
	
    $path=str_replace("\\","/",$path);	echo '[[[[[[['.$path.']]]]]';	
    $adir = explode('/',$path);
	//$adir = del_empty_var($adir);
	if(in_array('..',$adir))
	{
         return false;
	}
    $dirlist = '';
	print_r($adir);
    $rootdir = array_shift($adir);
	echo '[[[[[[['.$rootdir.']]]]]';

    if(!is_dir($rootdir)&&!mkdir($rootdir,0777))
	{
         return false;
	}

    foreach($adir as $val)
    {
         $dirlist .= "/".$val;
         $dirpath = $rootdir.$dirlist;
		 echo '((((('.$dirpath.')))))';
         if(!is_dir($dirpath)&& !mkdir($dirpath,0777))
         {
		       return false;
         }
         @chmod($dirpath,0777);
		 
    }	
	
    return $path;
}
*/

/**
*生成目录
**/
function get_dir($path){
	//这个\没考虑
				$newpath="";
    $path =str_replace("\\","/",$path);
	$ROOT_PATH =str_replace("\\","/",ROOT_PATH);
	$detail=explode("/",$path);
	foreach($detail AS $key=>$value){
		if($value==''&&$key!=0){
			//continue;
		}
		$newpath.="$value/";
		if((preg_match("/^\//i",$newpath)||preg_match("/:/i",$newpath))&&!strstr($newpath,$ROOT_PATH)){continue;}
		if( !is_dir($newpath) ){
			if(substr($newpath,-1)=='\\'||substr($newpath,-1)=='/')
			{
				$_newpath=substr($newpath,0,-1);
			}
			else
			{
				$_newpath=$newpath;
			}
			if(!is_dir($_newpath)&&!mkdir($_newpath)&&ereg("^\/",$ROOT_PATH)){
				return 'false';
			}
			@chmod($newpath,0777);
		}
	}
	return $path;
}



function random($length){ 
	$seed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
	$str = "";
	while(strlen($str) < $length){ 
		  $str .= substr($seed,(mt_rand() % strlen($seed)),1); 
	} 
	return $str; 
} 
/*
ip限制登入网站,被限制的ip返回ip号,未被限制则返回false
*/
function limit_ip($filedir='',$ip='')
{ 
    if(empty($ip))
	{
    $ip = get_ip();	
	}
	if(empty($ip))
	{
	 return false;
	}
	if(empty($filedir))
	{
	$dir = ROOT_PATH . '/scup/view/'.VIEW_TYPE.'/icon/icontempdata/'.LIMIT_IP_FILEDIR;	
	}
	else
	{
	$dir = $filedir;	
	}
	if(file_exists($dir))
	{
    $ipdata = @include($dir);	
	}
	else
	{
	 return false;
	}

    foreach($ipdata['data'] as $key => $value)
	{
	  if($value['datavalue']==$ip)
	  {
	   return $ip;
	  }
	} 
	
	return false; 
} 


/**
 * 获得用户的真实IP地址
 *
 * @return  string
 */
function get_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

	function filtrate($msg){
		//$msg = str_replace('&','&amp;',$msg);
		//$msg = str_replace(' ','&nbsp;',$msg);
		$msg = str_replace('"','&quot;',$msg);
		$msg = str_replace("'",'&#39;',$msg);
/*		$msg = str_replace("<","&lt;",$msg);
		$msg = str_replace(">","&gt;",$msg);
		$msg = str_replace("\t","   &nbsp;  &nbsp;",$msg);*/
		//$msg = str_replace("\r","",$msg);
		//$msg = str_replace("   "," &nbsp; ",$msg);
		return $msg;
	}
	function onethread($expires = '+10 seconds') {

		$now = time();
        $data = $now ;
		if (!is_numeric($expires)) {
			$expires = strtotime($expires, $now);
		}
        $filename = ROOT_PATH . '/temp/thread.php';;

		$timediff = $expires - $now;
		$filetime = false;

		if (file_exists($filename)) {
			$filetime = @filemtime($filename);
		}
	    if (file_exists($filename) && $filetime !== false) 
		{
				if ($filetime + $timediff < $now) 
				{
					if(is_writable(dirname($filename)))
					{
					@file_put_contents($filename, $data);
					}
					return 1 ;
				} else 
				{
				    sleep($now-$filetime);
					onethread();
				}
		}

		return 1 ;
	}


/**
* 字符截取
* @param string $string 要截取的字符串
* @param int $length 要截取的字符串长度
* @param string $dot 省略号
**/
function psp_cutstr($string, $length=20, $dot = '...') 
{
	if($length < 1 || ($len = strlen($string)) <= $length) return $string;
	
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

	$_string = '';
	if(strtolower(VIEW_CHARSET) == 'utf-8') 
	{

		$n = $tn = $noc = 0;
		while($n < $len) 
		{

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
			{
				$tn = 1; $n++; $noc++;
			}elseif(194 <= $t && $t <= 223)
			{
				$tn = 2; $n += 2; $noc += 2;
			}elseif(224 <= $t && $t <= 239)
			{
				$tn = 3; $n += 3; $noc += 2;
			}elseif(240 <= $t && $t <= 247)
			{
				$tn = 4; $n += 4; $noc += 2;
			}elseif(248 <= $t && $t <= 251)
			{
				$tn = 5; $n += 5; $noc += 2;
			}elseif($t == 252 || $t == 253)
			{
				$tn = 6; $n += 6; $noc += 2;
			}else
			{
				$n++;
			}

			if($noc >= $length) 
			{
				break;
			}
		}
		if($noc > $length) 
		{
			$n -= $tn;
		}
		$_string = substr($string, 0, $n);
	} else 
	{
		
		for($i = 0; $i < $length; $i++) 
		{
			if(!isset($string[$i])) break;
			
			$_string .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$_string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $_string);

	return $_string.$dot;
}

function sms_send($mob,$content){

	if(SMS_TYPE=='eshang8'){
		$url="http://sms.eshang8.cn/api/?esname=".SMS_ES_NAME."&key=".SMS_ES_KEY."&msg=$content&phone=$mob&smskind=1";
		if( !$msg=sockOpenUrl($url) ){
			//$msg=file_get_contents($url);
		}
		if($msg===''){
			return 0;
		}elseif($msg==='0'){
			return 1;			//发送成功
		}else{
			return $msg;
		}
	}elseif(SMS_TYPE=='winic'){
		$url="http://service.winic.org/sys_port/gateway/?id=".SMS_WI_ID."&pwd=".SMS_WI_PWD."&to=$mob&content=$content&time=";
		if( !$msg=sockOpenUrl($url) ){
			//$msg=file_get_contents($url);
		}
		if($msg===''){
			return 0;
		}
		$detail=explode("/",$msg);
		if($detail[0]==='000'){
			return 1;			//发送成功
		}else{
			return $detail[0];
		}
	}else{
		$notice = &get_message(array('msg'=>'系统没有选择短信接口平台!','url'=>'','title'=>'Notice'));
		$notice ->display();	
	}
}

//sock方式打开远程文件
function sockOpenUrl($url,$method='GET',$postValue=''){
	$method = strtoupper($method);
	if(!$url){
		return '';
	}elseif(!preg_match("/^http:\/\//i", $url)){
		$url="http://$url";
	}
	$urldb=parse_url($url);
    if(!isset($urldb['port'])){ $urldb['port']='';}
    if(!isset($urldb['host'])){ $urldb['host']='';}	
    if(!isset($urldb['query'])){ $urldb['query']='';}
    if(!isset($urldb['path'])){ $urldb['path']='';}
	$file ='';		
	$port=$urldb['port']?$urldb['port']:80;
	$host=$urldb['host'];
	$query='?'.$urldb['query'];
	$path=$urldb['path']?$urldb['path']:'/';
	$method=$method=='GET'?"GET":'POST';

	$fp = fsockopen($host, 80, $errno, $errstr, 30);
	if(!$fp)
	{
		echo "$errstr ($errno)<br />\n";
	}
	else
	{
		$out = "$method $path$query HTTP/1.1\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Cookie: c=1;c2=2\r\n";
		$out .= "Referer: $url\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Connection: Close\r\n";
		if ( $method == "POST" ) {
			$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
			$length = strlen($postValue);
			$out .= "Content-Length: $length\r\n";
			$out .= "\r\n";
			$out .= $postValue;
		}else{
			$out .= "\r\n";
		}
		fwrite($fp, $out);
		while (!feof($fp)) {
			$file.= fgets($fp, 256);
		}
		fclose($fp);
		if(!$file){
			return '';
		}
		$ck=0;
		$string='';
		$detail=explode("\r\n",$file);
		foreach( $detail AS $key=>$value){
			if($value==''){
				$ck++;
				if($ck==1){
					continue;
				}
			}
			if($ck){
				$stringdb[]=$value;
			}
		}
		$string=implode("\r\n",$stringdb);
		//$string=preg_replace("/([\d]+)(.*)0/is","\\2",$string);
		return $string;
	}
}


?>